<template>
    <div style="padding: 0 17px">
        <Breadcrumb/>
        <div style="display: flex;flex-wrap: wrap; margin-top: 20px;">
            <el-button type="primary" style="margin-right: 15px" @click="addItem">新增
            </el-button>
            <span style="min-width: 150px;margin-right: 15px">
        <OrganizationTree
                @change="load"
                @tree-select-changed="treeSelectChanged"
                v-model="selectedOrganizationId"
        />
      </span>
            <el-input v-model="searchClientName" placeholder="单位名称"
                      style="width: 300px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
            <el-input v-model="searchName" placeholder="设备名称"
                      style="width: 300px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
            <el-input v-model="searchDeviceNum" placeholder="设备序列号"
                      style="width: 300px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
            <el-input v-model="searchMonitorNum" placeholder="监控点编号"
                      style="width: 300px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
            <el-button icon="Search" type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;"
                       @click="load">搜索
            </el-button>
            <el-button type="success" style="" @click="importData">导入</el-button>
            <el-button type="success" style="" @click="exportData">导出</el-button>
        </div>

        <el-table :data="tableData" :row-style="{ height: '77px' }" border
                  style="width: calc(100vw - 240px);margin-top: 20px;height: 70vh;color: #909399;font-size: 15px;">
            <el-table-column prop="id" label="ID" width="100"/>
            <el-table-column prop="name" label="设备名称" width="200"/>
            <el-table-column prop="deviceId" label="设备编号" width="200"/>
            <el-table-column prop="clientName" label="单位名称" width="200"/>
            <el-table-column prop="equipmentId" label="监控设备识别码" width="150"/>
            <el-table-column prop="equipmentName" label="监控设备名" width="150"/>
            <el-table-column prop="simId" label="SIM卡号" width="180"/>
            <el-table-column prop="deviceBrand" label="设备品牌" width="200"/>
            <el-table-column prop="accessProtocol" label="接入协议" width="110"/>
            <el-table-column prop="ipPort" label="IP地址及端口号" width="110"/>
            <el-table-column prop="organizationName" label="组织" width="300"/>
            <el-table-column prop="deviceNum" label="设备序列号" width="150"/>
            <el-table-column prop="monitorNum" label="监控点编号" width="150"/>
            <el-table-column prop="appKey" label="appKey" width="150"/>
            <el-table-column prop="secret" label="secret" width="150"/>
            <el-table-column prop="explanation" label="说明" width="300"/>
            <el-table-column align="center" label="操作" fixed="right" width="180">
                <template v-slot="scope">
                    <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
                    <el-button v-if="this.userInformation.role === 1" type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :background="true"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
        <el-dialog title="监控操作" v-model="operationItemDialog" :close-on-click-modal="false" :show-close="false"
                   width="700">
            <el-form label-position="top" :inline="true" :model="form" ref="form" :rules="rules">
                <el-form-item label="设备名称" prop="name">
                    <el-input placeholder="设备名称" v-model="form.name"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="设备编号" prop="deviceId">
                    <el-input placeholder="设备编号" v-model="form.deviceId"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="appKey" prop="appKey">
                    <el-input placeholder="海康提供的appKey" v-model="form.appKey"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="secret" prop="secret">
                    <el-input placeholder="海康提供的secret" v-model="form.secret"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="单位名称" prop="clientId">
                    <el-select v-model="form.clientId" filterable placeholder="选择单位名称">
                        <el-option
                                v-for="item in clientOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="监控的设备识别码" prop="equipmentId">
                    <el-input placeholder="监控的设备识别码" v-model="form.equipmentId"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="SIM卡" prop="simId">
                    <el-input placeholder="SIM卡" v-model="form.simId"
                              autocomplete="off"></el-input>
                </el-form-item>
                <!--<el-form-item label="SIM卡"-->
                              <!--prop="simId">-->
                    <!--<el-dropdown trigger="click">-->
                        <!--<el-select v-model="form.simId" ref="selectRef1" placeholder="请选择SIM卡"-->
                                   <!--:visibleChange="closeSelect" :focus="closeSelect">-->
                        <!--</el-select>-->
                        <!--<template #dropdown>-->
                            <!--<el-input v-model="searchSim" placeholder="请输入SIM卡号"-->
                                      <!--style="margin: 5px;width: 200px;height: 33px;font-size: 13px;"-->
                                      <!--clearable></el-input>-->
                            <!--<el-dropdown-menu style="width: 200px">-->
                                <!--<el-dropdown-item-->
                                        <!--v-for="option in simOptions"-->
                                        <!--:value="option.id"-->
                                        <!--:label="option.simId"-->
                                        <!--@click="selectedSim(option)">-->
                                    <!--{{option.simId}}-->
                                <!--</el-dropdown-item>-->
                            <!--</el-dropdown-menu>-->
                            <!--<div style="display: flex;margin: 0 auto;max-width: 80px">-->
                                <!--<el-pagination-->
                                        <!--small-->
                                        <!--@size-change="innerHandleSizeChange"-->
                                        <!--@current-change="innerHandleCurrentChange"-->
                                        <!--:current-page="simCurrentPage"-->
                                        <!--:page-size="simPageSize"-->
                                        <!--layout="prev, pager, next, "-->
                                        <!--:total="simTotal"-->
                                <!--&gt;-->
                                <!--</el-pagination>-->
                            <!--</div>-->
                        <!--</template>-->
                    <!--</el-dropdown>-->
                <!--</el-form-item>-->
                <el-form-item label="组织" prop="organization">
                    <OrganizationTree
                            v-model="form.organization"
                    />
                </el-form-item>
                <el-form-item label="设备品牌" prop="deviceBrand">
                    <el-input placeholder="设备品牌" v-model="form.deviceBrand"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="接入协议" prop="accessProtocol">
                    <el-input placeholder="接入协议" v-model="form.accessProtocol"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label-width="110" label="IP地址及端口号" prop="ipPort">
                    <el-input placeholder="IP地址及端口号" v-model="form.ipPort"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="设备序列号" prop="deviceNum">
                    <el-input placeholder="设备序列号" v-model="form.deviceNum"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="监控点编号" prop="monitorNum">
                    <el-input placeholder="监控点编号" v-model="form.monitorNum"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="说明" prop="explanation">
                    <el-input type="textarea" placeholder="说明" style="width: 600px" v-model="form.explanation"
                              autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reset('form')">取 消</el-button>
                <el-button type="primary" @click="submitForm('form')">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="导入" v-model="dialogImportVisible" width="520px">
            <el-form label-position="right" label-width="100px">
                <el-form-item label="模板下载:" padding-top:10px>
                    <el-button type="primary" size="small" style="" @click="exportTemplate">监控列表</el-button>
                </el-form-item>
                <el-form-item label="文件" padding-top:-20px>
                    <el-upload :headers="headers"
                           :multiple="false"
                               :on-success="onUploadSuccess"
                               :on-error="onUploadError"
                               :action="serverIp+'/video-device/importData'"
                               class="upload-demo">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogImportVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import request from "@/utils/request.js";
    import OrganizationTree from "@/components/OrganizationTree.vue";
    import Breadcrumb from "@/components/Breadcrumb.vue";
    import {serverIp} from "../../../public/static/config"

    export default {
        name: "VideoList",
        components: {Breadcrumb, OrganizationTree},
        data() {
            return {
                serverIp,
                headers: {
                    token:  JSON.parse(localStorage.getItem('user')).token,
                },
                dialogImportVisible: false,
                userInformation: JSON.parse(localStorage.getItem("user")),
                currentData: {},
                selectedOrganizationId: JSON.parse(localStorage.getItem("user")).organization,
                searchClientName: '',     // 搜索框
                searchName: '',
                searchDeviceNum: '',
                searchMonitorNum: '',
                tableData: [],  // 表单
                currentPage: 1,
                pageSize: 10,
                total: 0,
                operationItemDialog: false,  // 弹窗
                form: {},        // 编辑Sim信息赋值
                searchSim: '',
                selectOptionName: '',
                simOptions: [],
                clientOptions: [],
                simCurrentPage: 1,
                simPageSize: 10,
                simTotal: 0,
                rules: {
                    name: [
                        {required: true, message: '请输入设备名', trigger: 'blur'},
                    ],
                    clientId: [
                        {required: true, message: '请选择单位名称', trigger: 'blur'},
                    ],
                    organization: [
                        {required: true, message: '请选择组织', trigger: 'blur'},
                    ],
                    deviceId: [
                        {required: true, message: '请输入设备编号', trigger: 'blur'},
                    ],
                    deviceNum: [
                        {required: true, message: '请输入设备序列号', trigger: 'blur'},
                    ],
                    monitorNum: [
                        {required: true, message: '请输入监控点编号', trigger: 'blur'},
                    ],
                    appKey: [
                        {required: true, message: '请输入海康提供的appKey', trigger: 'blur'},
                    ],
                    secret: [
                        {required: true, message: '请输入海康提供的secret', trigger: 'blur'},
                    ],
                },
                isEdit: false,
            }
        },
        mounted() {
            // 初始化加载用户数据
            this.load()
            // this.getSimOptions()
            this.getClientOptions()
        },

        methods: {
            importData() {
                this.dialogImportVisible = true;
            },
            onUploadSuccess() {
                this.$message.success('上传成功');
                this.dialogImportVisible = false;
                location.reload();
            },
            onUploadError(){
                this.$message.error('上传失败');
            },
            // 模板下载
            exportTemplate() {
                window.location.href = '../xlsx/videoDevice.xlsx'
            },
            exportData() {
                let level = JSON.parse(localStorage.getItem("user")).level
                if (this.currentData.level !== undefined) {
                    level = this.currentData.level
                }
                let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
                } else {
                    clientIds = [];
                }
                window.open(serverIp + '/video-device/export?clientName='+this.searchClientName + "&name="+this.searchName+"&deviceNum="+this.searchDeviceNum+"&monitorNum="+this.searchMonitorNum+
                "&level=" + level + "&organizationId=" + this.selectedOrganizationId + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds);
            },
            getClientOptions() {
                let level = JSON.parse(localStorage.getItem("user")).level
                let organizationId = JSON.parse(localStorage.getItem("user")).organization
                let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
                } else {
                    clientIds = [];
                }
                request.get("/client/listbyName?name=" + this.selectOptionName + "&organizationId=" + organizationId + "&level=" + level + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
                    this.clientOptions = res.data
                })
            },
            closeSelect() {
                this.$refs["selectRef"].blur();
            },
            // 选择绑定SIM
            selectedSim(option) {
                this.form.simInputStoreId = option.id
                this.form.simId = option.simId
            },
            innerHandleCurrentChange(item) {
                // 改变当前页码触发
                this.simCurrentPage = item
                this.getSimOptions()
            },
            innerHandleSizeChange(item) {   // 改变当前每页的个数触发
                this.simPageSize = item
                this.getSimOptions()
            },
            // 获取要绑定的SIM列表
            getSimOptions() {
                let level = JSON.parse(localStorage.getItem("user")).level
                let organizationId = JSON.parse(localStorage.getItem("user")).organization
                let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
                } else {
                    clientIds = [];
                }
                request.get("/sim-input-store/all?pageNum=" + this.simCurrentPage + "&pageSize=" + this.simPageSize + "&SIMId=" + this.searchSim + "&organizationId=" + organizationId + "&level=" + level + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
                    for (let key in res.data) {
                        if (key === "record") {
                            this.simOptions = res.data[key];
                        } else if (key === "total") {
                            this.simTotal = res.data[key];
                        }
                    }
                })
            },
            // 搜索及初始化
            load() {
                let level = JSON.parse(localStorage.getItem("user")).level
                if (this.currentData.level !== undefined) {
                    level = this.currentData.level
                }
                let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
                } else {
                    clientIds = [];
                }
                request.get("/video-device/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&clientName="+this.searchClientName + "&name="+this.searchName+"&deviceNum="+this.searchDeviceNum+"&monitorNum="+this.searchMonitorNum+
                    "&level=" + level + "&organizationId=" + this.selectedOrganizationId + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
                    if (res.code === '200') {
                        for (let key in res.data) {
                            if (key === "record") {
                                this.tableData = res.data[key];
                            } else if (key === "total") {
                                this.total = res.data[key];
                            }
                        }
                    } else {
                        this.$message.error("错误" + res.msg)
                    }
                })
            },
            // 新增
            addItem() {
                this.operationItemDialog = true
            },
            // 编辑
            editItem(scope) {
                this.isEdit = true;
                Object.assign(this.form, scope)
                this.operationItemDialog = true
            },
            // 编辑、新增确定按钮
            submitForm(val) {
                this.form.operatorId = JSON.parse(localStorage.getItem("user")).id
                this.$refs[val].validate((valid) => {
                    if (valid) {
                        request.post("/video-device/edit", this.form).then(res => {
                            if (res.code === '200') {
                                this.$message({
                                    message: "成功",
                                    type: "success"
                                })
                                this.load()
                                if (!this.isEdit) {
                                    this.clearConditions()
                                }
                                this.reset(val)
                            } else {
                                this.$message.error("操作失败" + res.msg)
                            }
                        })
                    }
                })
            },
            // 清空查询条件
            clearConditions() {
                this.selectedState = ""
                this.selectedOrganizationId = JSON.parse(localStorage.getItem("user")).organization;
                this.search = "";
            },
            reset(val) {
                this.isEdit = false;
                this.operationItemDialog = false;
                this.form = {};
                this.$refs[val].clearValidate();
            },
            // 删除确定弹窗
            deleteItem(scope) {
                this.$confirm('是否确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.delete("/video-device/delete/" + scope).then(res => {
                        if (res.code === '200') {
                            this.$message.success("成功")
                            this.load()
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                });
            },
            treeSelectChanged(data) {
                this.currentData = data
            },
            handleSizeChange(pageSize) {   // 改变当前每页的个数触发
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {  // 改变当前页码触发
                this.currentPage = pageNum
                this.load()
            },
        }
    }
</script>

<style scoped>
    :deep(.el-table th .cell) {
        font-weight: 700
    }

    .el-select {
        width: var(--el-form-width);
    }

    .el-input {
        width: var(--el-form-width);
    }
</style>
